package com.epfresh.supplier.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epfresh.api.adapter.CommonAdapter;
import com.epfresh.api.adapter.ViewHolder;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.entity.TagPager;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.CustomDialog;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.OrderSurePrepareDialog;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.supplier.R;
import com.epfresh.supplier.adapter.OrderAdapter;
import com.epfresh.supplier.adapter.OrderAgentAdapter;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.OrderAgentCode;
import com.epfresh.supplier.entity.OrderAgentList;
import com.epfresh.supplier.entity.OrderListBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderAgentSearchActivity extends BaseActivity implements LoadMoreListView.IXListViewListener{

	static final String TAG = "OrderSearchActivity";
	ImageView ivBack;
	ImageView ivSearch;
	EditText etContent;
	TextView tvSearch;

	ImageView ivDelete;
	View rlHistory,rlContent;

	ListView lvHistory;
	LoadMoreListView lvContent;

	SharedPreferences sharedPreferences;
	SharedPreferences.Editor editor;
	List<String> historyList = new ArrayList<String>();
	StringAdapter historyAdapter;
	String historyTogether;

	ArrayList<String> hotList = new ArrayList<>();


	private List<OrderAgentList> list = new ArrayList<>();

	OrderAgentAdapter adapter;
	protected View mainView;
	protected View vException;
	private int requestSucceedCount = 0;
	private int PAGE_SIZE = 10;


	private TagPager tagPager = new TagPager();
	Context context;
	int postionFlag;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = mContext;
		initShare();
		initView();
		//loadData(tagPager.getNumber());
	}
	private void initView() {
		setContentView(R.layout.activity_order_search);
		rlContent = findViewById(R.id.rl_content);
		rlHistory = findViewById(R.id.rl_history);
		lvHistory = (ListView)findViewById(R.id.lv_history);
		lvContent = (LoadMoreListView)findViewById(R.id.lv_content);

		Log.i("initView", historyTogether + "——————————————————————————————————");//
		historyAdapter = new StringAdapter(this,historyList,R.layout.item_string);
		initHistory();
		lvHistory.setAdapter(historyAdapter);
		ivBack = (ImageView) findViewById(R.id.iv_back);
		etContent = (EditText)findViewById(R.id.et_content);
		tvSearch = (TextView)findViewById(R.id.tv_search);
		tvSearch.setOnClickListener(this);
		ivDelete = (ImageView)findViewById(R.id.iv_delete);
		ivDelete.setOnClickListener(this);
		ivBack.setOnClickListener(this);

		vException = findViewById(R.id.v_exception);
		mainView = findViewById(R.id.fragment_ptr_home_ptr_frame);
		initHeadView();
		tagPager.setNumber(0);
		// initContentList(type);
		list = new ArrayList<>();
		adapter = new OrderAgentAdapter(context,lvContent, list);
		adapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View v, int position, long l) {
				Log.e("new onItemClick",""+position);

// 交货码，查看物流，取消订单，确认收货，支付， 详情
				switch (v.getId()) {
					case R.id.ll_order:
					case R.id.rl_more:
					case R.id.ll_images:
/*                        Intent detail = new Intent(context, H5OrderDetailActivity.class);
                        detail.putExtra("orderId", list.get(position).getId());
                        detail.putExtra(com.epfresh.api.constant.Constant.KEY_WEB_URL, "http://m.epfresh.com/help/order_supply_new.html?orderId=" + list.get(position).getId());
                        detail.putExtra(com.epfresh.api.constant.Constant.KEY_WEB_TITLE, "订单详情");
                        startActivityForResult(detail,0x002);*/
						break;

					case R.id.tv_item_order_agent_goods_code:
						requestCode(list.get(position).getId());
						break;
					case R.id.ll_item_order_agent:
						Intent detail = new Intent(context, OrderDetailAgentActivity.class);
						detail.putExtra("id", list.get(position).getId());
						context.startActivity(detail);
						break;

				}
			}
		});


		lvContent.setXListViewListener(this);
		lvContent.setAdapter(adapter);
		View rlNoDate = findViewById(R.id.rl_nodate);
		lvContent.setEmptyView(rlNoDate);

		etContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

				if (actionId == EditorInfo.IME_ACTION_SEARCH) {

					if (TextUtils.isEmpty(etContent.getText().toString())) {
						return true;
					}
					tagPager.setNumber(0);
					lvContent.resetNoMore();
					requestSucceedCount = 0;
					rlHistory.setVisibility(View.GONE);
					rlContent.setVisibility(View.VISIBLE);
					loadData(0);
					editor.putString("order_history", sharedPreferences.getString("order_history", "") + "," + etContent.getText().toString());
					editor.commit();
					return true;
				}
				return false;
			}
		});
	}

	private Dialog dialogCancel;
	TextView[] numbers = new TextView[6];
	void showCodeDialog(String code){
		if (dialogCancel == null) {
			View view = LayoutInflater.from(context).inflate(R.layout.dialog_code, null);
			dialogCancel = new Dialog(context, R.style.ActionSheetDialogStyle);
			dialogCancel.setContentView(view);
			Window dialogWindow = dialogCancel.getWindow();
			if(dialogWindow==null)
				return;
			dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
			WindowManager.LayoutParams lp = dialogWindow.getAttributes();
			lp.width = LocalDisplay.SCREEN_WIDTH_PIXELS;
			dialogWindow.setAttributes(lp);
			numbers[0] = (TextView)view.findViewById(R.id.number1);
			numbers[1] = (TextView)view.findViewById(R.id.number2);
			numbers[2] = (TextView)view.findViewById(R.id.number3);
			numbers[3] = (TextView)view.findViewById(R.id.number4);
			numbers[4] = (TextView)view.findViewById(R.id.number5);
			numbers[5] = (TextView)view.findViewById(R.id.number6);
		}
		for(int i=0;i<6;i++){
			numbers[i].setText(""+code.charAt(i));
		}
		dialogCancel.show();
	}



	private void initHeadView() {
		ptrFrameLayout = (PtrFrameLayout) findViewById(R.id.fragment_ptr_home_ptr_frame);
		ptrFrameLayout.setPtrHandler(ptrHandler);
	}
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.e("resultCode",""+resultCode+"__"+requestCode);

		if (resultCode == 0x002 && requestCode == 0x002) {
			Log.e("result","shuaxin");
			refresh();
		}
	}
	private PtrFrameLayout ptrFrameLayout;
	private PtrHandler ptrHandler = new PtrHandler() {
		@Override
		public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
			return PtrDefaultHandler.checkContentCanBePulledDown(frame, lvContent, header);
		}

		@Override
		public void onRefreshBegin(PtrFrameLayout frame) {
			refresh();
		}
	};

	boolean refreshFlag = false;

	public void refresh() {
		if(lvContent==null)
			return;
		lvContent.resetNoMore();
		requestSucceedCount = 0;
		refreshFlag = true;
		loadData(0);
	}
	@Override
	public void onLoadMore() {
		int number = tagPager.getNumber();
		loadData(number + 1);
		//initContentList(number + 1);
	}

	public void updateViewStatus(RequestTag requestTag) {
		ptrFrameLayout.refreshComplete();
		if (tagPager.isLast()) {
			lvContent.noMore();
		} else {
			lvContent.stopLoadMore();
		}
	}

	void loadData(int page){
/*        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd("buy/homepage/filters");
        RequestEntityMapSupply.putParameter("all", true);
        request(RequestEntityMapSupply, "buy/homepage/filters", onRequestListener);*/
		RequestEntitySupply<Map<String, String>> entity = new RequestEntitySupply<>();
		Map<String, String> map = new HashMap<>();
		map.put("agencyStoreId", BaseApplication.getInstance().getStoreId());
		if(TextUtils.isEmpty(etContent.getText()))
			return;
		map.put("keyword", etContent.getText().toString());
		map.put("pageNumber", page + "");
		map.put("pageSize", PAGE_SIZE + "");
		entity.setCmd("pm-order/baseorder/groupon/agencylist");
		entity.setParameters(map);
		RequestTag requestTag = new RequestTag();
		requestTag.tag = "pm-order/baseorder/groupon/agencylist";
		requestTag.action = page;

		requestTag.type = RequestTag.TYPE_CURRENT;
		request(entity, requestTag, onRequestListener);
	}

	OnRequestListener<ContentEntity<OrderAgentList>> onRequestListener = new OnRequestListener<ContentEntity<OrderAgentList>>() {
		@Override
		public ContentEntity<OrderAgentList> jsonToObj(String responseStr) {
			return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<OrderAgentList>>() {
			}.getType());
		}

		@Override
		public void onFail(int failCode, Object arg, Object tag) {
			RequestTag requestTag = (RequestTag) tag;
			updateViewStatus(requestTag);
			if (requestSucceedCount == 0){
				showExceptionView(R.mipmap.order_no, "网络问题,请点击重试", HttpRequest.FAIL_NET_FAULT);
			}
		}

		@Override
		public void onResponseError(int failCode, Object arg, Object tag) {
			if (requestSucceedCount == 0){
				showExceptionView(R.mipmap.order_no, arg + "", HttpRequest.FAIL_NET_FAULT);//arg + ",请点击重试"
			}
			RequestTag requestTag = (RequestTag) tag;
			updateViewStatus(requestTag);
		}

		@Override
		public void onStart(Object tag) {
			if (requestSucceedCount == 0 && !refreshFlag){
				showProgressView();
			}else
				refreshFlag = false;
		}

		@Override
		public void onResponse(ResponseEntity<ContentEntity<OrderAgentList>> response, Object tag) {
			//页面第一次调用网络请求接口并成功
			showMainView();
			RequestTag requestTag = (RequestTag) tag;
			if (requestTag.action == 0||requestSucceedCount==0) {
				list.clear();
			}
			requestSucceedCount ++;

			ContentEntity<OrderAgentList> orderResponse = response.getResponseElement();
			List<OrderAgentList> content = orderResponse.getContent();
			tagPager.setLast(orderResponse.getLast());
			tagPager.setNumber(orderResponse.getNumber());
			tagPager.setSize(orderResponse.getSize());
			tagPager.setTotalElements(orderResponse.getTotalElements());
			list.addAll(content);
			adapter.notifyDataSetChanged();
			if(orderResponse.getNumber()==0){
				lvContent.setSelection(0);
			}
			updateViewStatus(requestTag);
			if(list.size()==0){
				showExceptionView(R.mipmap.order_no, "暂无订单", HttpRequest.FAIL_DATA_EMPTY);
			}
		}
	};


	void initShare(){
		sharedPreferences = getSharedPreferences("search_history", Context.MODE_PRIVATE); //私有数据
		editor = sharedPreferences.edit();//获取编辑器
	}
	void initHistory(){
		historyTogether = sharedPreferences.getString("order_history","");
		Log.i("historyTogether",historyTogether+"——————————————————————————————————");
		historyList.clear();
		if(!historyTogether.equals("")){
			ArrayList<String> flag = new ArrayList<>();
			flag.addAll(Arrays.asList(historyTogether.split(",")));
			for(int i=flag.size()-1;i>0;i--){
				if(!historyList.contains(flag.get(i)))
					historyList.add(flag.get(i));
				if(historyList.size()==10)
					break;
			}
		}
		historyAdapter.notifyDataSetChanged();
	}
	protected View getToolBar() {
		View actionbar = this.inflaterView(R.layout.toolbar_search, (ViewGroup)null);
		((EditText)actionbar.findViewById(R.id.et_content)).setHint("请输入订单号、商品标题");//("请输入收货人姓名、手机号、订单号");
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(-1, this.getResources().getDimensionPixelSize(com.epfresh.api.R.dimen.action_bar_height));
		actionbar.setLayoutParams(lp);
		return actionbar;
	}
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.iv_back:
				// 返回上一页
				finish();
				break;
			case R.id.tv_search:
				if (TextUtils.isEmpty(etContent.getText().toString())){
					return;
				}
				tagPager.setNumber(0);
				lvContent.resetNoMore();
				requestSucceedCount = 0;

				/*Intent goodsList = new Intent(this, OrderListActivity.class);
				goodsList.putExtra("title", etContent.getText().toString());
				startActivity(goodsList);*/
				rlHistory.setVisibility(View.GONE);
				rlContent.setVisibility(View.VISIBLE);
				//refresh();
				loadData(0);
				editor.putString("order_history", sharedPreferences.getString("order_history", "") + "," + etContent.getText().toString());
				editor.commit();
				break;
			case R.id.iv_delete:
				CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
				builder.setMessage("确定要删除历史搜索吗？");//设置显示的内容
				//builder.setTitle("提示");
				builder.setTitleVisible(false);
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
					@Override
					public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
						// mHttpSure();
						editor.putString("order_history", "");
						editor.commit();
						Log.i("iv_delete", historyTogether + "——————————————————————————————————");
						initHistory();
						dialog.dismiss();
					}
				});
				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
					@Override
					public void onClick(DialogInterface dialog, int which) {//响应事件
						dialog.dismiss();
					}

				});
				builder.create().show();
			default:
				break;
		}
	}

	class StringAdapter extends CommonAdapter<String>{
		public StringAdapter(Context context, List<String> historyList, int a) {
			super(context, historyList, a);
		}

		@Override
		public void convert(ViewHolder holder, final String bean) {
			holder.setText(R.id.tv_string, bean);
			holder.setOnClickListener(R.id.tv_string, new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					etContent.setText(bean);
					etContent.setSelection(bean.length());
					tvSearch.performClick();
				}
			});
		}
	}



	void requestCode(String id){
		RequestEntitySupply<Map<String, String>> entity = new RequestEntitySupply<>();
		Map<String, String> map = new HashMap<>();
		map.put("grouponId", id);
		entity.setCmd("pm-order/baseorder/groupon/inspectCode");
		entity.setParameters(map);
		RequestTag requestTag = new RequestTag();
		requestTag.tag = "pm-order/baseorder/groupon/inspectCode";
		request(entity, requestTag, onRequestCodeListener);
	}

	OnRequestListener<OrderAgentCode> onRequestCodeListener = new OnRequestListener<OrderAgentCode>() {
		@Override
		public OrderAgentCode jsonToObj(String responseStr) {
			return new Gson().fromJson(responseStr, OrderAgentCode.class);
		}

		@Override
		public void onFail(int failCode, Object arg, Object tag) {
			T.toast("请求失败，请重试");
			hideProgressDialog();
		}

		@Override
		public void onResponseError(int failCode, Object arg, Object tag) {
			T.toast("请求失败，请重试");
			hideProgressDialog();

		}

		@Override
		public void onStart(Object tag) {
			//showProgressView();
			showProgressDialog();
		}

		@Override
		public void onResponse(ResponseEntity<OrderAgentCode> response, Object tag) {
			//页面第一次调用网络请求接口并成功
			hideProgressDialog();
			OrderAgentCode orderResponse = response.getResponseElement();
			showCodeDialog(orderResponse.getInspectCode());
		}
	};


}
